package com.ruoyi.common.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author yeoman
 * @date 2025/4/10 21:07
 * @description 通过该类即可在普通工具类里获取spring管理的bean
 */
@Component
public class SpringContextTool implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextTool.applicationContext == null) {
            SpringContextTool.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> type) {
        return getApplicationContext().getBean(type);
    }
}
